package com.safety.hat.service.impl.admin;

import com.alibaba.fastjson.JSONObject;
import com.safety.hat.data.ACTEnum;
import com.safety.hat.data.admin.AdminLoginBO;
import com.safety.hat.data.admin.AdminLoginDTO;
import com.safety.hat.service.admin.adpater.IAdminSocketUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Date: 2020/5/25 0:06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminSocketUserServiceImpl implements IAdminSocketUserService<AdminLoginBO> {

    private static final String DEFAULT = "admin";
    private static final ConcurrentHashMap<String, Session> userMap = new ConcurrentHashMap<>(64);

    /**
     * 处理消息
     */
    @Override
    public void handleMessage(AdminLoginBO message, Session session) {
        if (DEFAULT.equals(message.getUserName())) {
            AdminLoginDTO.AdminInfo adminInfo = AdminLoginDTO.AdminInfo.builder()
                    .adminId("1")
                    .userName(DEFAULT)
                    .build();
            AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
            adminLoginDTO.setAdminInfo(adminInfo);
            adminLoginDTO.setCmd(ACTEnum.ADMIN_LOGIN.getAct());
            adminLoginDTO.setMsg("登陆成功");
            adminLoginDTO.setStatus(true);
            session.getAsyncRemote().sendText(JSONObject.toJSONString(adminLoginDTO));
            //缓存当前登录消息
            userMap.put(message.getUserName(), session);
        } else {
            AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
            adminLoginDTO.setCmd(ACTEnum.ADMIN_LOGIN.getAct());
            adminLoginDTO.setMsg("登陆失败,用户名或密码错误！");
            adminLoginDTO.setStatus(false);
            session.getAsyncRemote().sendText(JSONObject.toJSONString(adminLoginDTO));
        }
    }

    /**
     * 删除信息
     */
    @Override
    public void removeInfo(Session session) {
        Optional<String> removeKey = userMap.entrySet().stream()
                .filter(entry -> entry.getValue().equals(session))
                .map(entry -> entry.getKey())
                .findAny();
        log.info("删除缓存连接：sessionId = {},removeKey = {}", session.getId(), removeKey);
        if (removeKey.isPresent() && StringUtils.isNoneBlank(removeKey.get())) {
            userMap.remove(removeKey.get());
        }
    }

    /**
     * 获取所有的会话
     */
    @Override
    public List<Session> getAllSession() {
        return userMap.values().stream().collect(Collectors.toList());
    }

    /**
     * 根据当前行为判断是否可以被处理
     */
    @Override
    public boolean canHandle(String act) {
        return ACTEnum.ADMIN_LOGIN.is(act);
    }

    @Override
    public Class<AdminLoginBO> getMessageClass() {
        return AdminLoginBO.class;
    }

}
    

